package com.xbdun.web.bmp.controller.base;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xbdun.common.enums.XbdunPkgEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.qr.LoginMacResponse;
import com.xbdun.comweb.bmp.session.CurrentUserInfo;
import com.xbdun.comweb.bmp.util.UserInfoUtil;
import com.xbdun.comweb.bmp.util.WebCommonUtil;
import com.xbdun.facade.bmp.constant.DubboBmpConst;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.response.system.QueryOrgUsersResponse;
import com.xbdun.facade.bmp.service.system.OrgUserFacade;
import com.xbdun.facade.bmp.service.system.PlatfromFacade;
import com.xbdun.web.bmp.controller.system.BaseSystemController;
import com.xbdun.web.bmp.util.LoginSkipUtil;

/**
* @ClassName: IndexController
* @Description: 初始化页面
* @author zhanggt 360730440@qq.com
* @date 2017年4月14日 上午11:42:21
 */
@Controller
public class ComPageController extends BaseSystemController{
	//机构用户
	@Reference(registry=DubboBmpConst.REGISTRYS)
	OrgUserFacade orgUserFacade;
	//获取平台密钥
	@Reference(registry=DubboBmpConst.REGISTRYS)
	PlatfromFacade platfromFacade;
	/**
	* 登录成功后后台管理画面
	* @Title: mangerIndex
	* @Description 后台登陆初始化页面
	* @return String    返回类型
	 */
	@RequestMapping("error500")
	public ModelAndView error500(ModelAndView view,HttpServletRequest request){
		view.setViewName("error/error500");
		view.addObject("msg",StringUtils.defaultIfBlank((String)request.getParameter("msg"),"系统繁忙，请稍后再试"));
		view.addObject("errorCode",StringUtils.defaultIfBlank((String)request.getParameter("errorCode"),"500"));
		view.addObject("backUrl",StringUtils.defaultIfBlank((String)request.getParameter("backUrl"),WebCommonUtil.getLoginUrl()));
		return view;
	}
	
	//发用邮件成功
	@RequestMapping("emailOk")
	public ModelAndView emailSuccess(ModelAndView view){
		
		view.setViewName("system/emailSuccess");
		return view;
	}
	
	//用户真正去登陆
	@RequestMapping(path="loginMac",method=RequestMethod.POST)
	public ModelAndView realyLogin(@RequestBody @RequestParam("loginData")String loginData){
		ModelAndView view = new ModelAndView();
		LoginMacResponse parseObject = null;
		try{
			//退出当前用户登录
			UserInfoUtil.loginOut(getRequest());
			// 校验登录信息
			parseObject = LoginSkipUtil.chekedRealyLoginQr(WebCommonUtil.getIpAddr(getRequest()),loginData,platfromFacade);
			XbdunPkgEnum enum1 = XbdunPkgEnum.getEnum(parseObject.getPkgName());
			if (null == enum1) {
				throw BmpBizException.LOGIN_QR_MAC_FAIL.newInstance("登录的来源不系统未定义");
			}
			//真正获取用户去登陆
			QueryOrgUsersResponse userInfo = orgUserFacade.getUserByOrgUserCode(parseObject.getOrgCode(),parseObject.getUserCode());
			if(null == userInfo){
				throw BmpBizException.DB_SELECTONE_IS_NULL.newInstance("对不起,您的数据在传输中被修改，用户不存在;");
			}
			
			//真正的用户登录成功
			CurrentUserInfo currentUserInfo = new CurrentUserInfo();
			
        	currentUserInfo.setMobile(userInfo.getMobile());//用户电话
        	currentUserInfo.setOrgCode(userInfo.getOrgCode());//机构编号
        	currentUserInfo.setUserCode(String.valueOf(parseObject.getUserCode()));//用户编号
        	currentUserInfo.setOrgName(userInfo.getOrgName());//机构名称
        	currentUserInfo.setUserId(userInfo.getUserId());//用户对应机构用户ID
        	currentUserInfo.setRoleId(userInfo.getRoleId());//角色ID
        	currentUserInfo.setPlatCode(parseObject.getPlatCode());//登录平台Code
        	currentUserInfo.setUserName(userInfo.getRealName());//用户的真实姓名
        	currentUserInfo.setJonNum(userInfo.getJonNum());//员工工号
			UserInfoUtil.setCurrentUserInfo(getRequest(), currentUserInfo);
			//删除本地缓存
			UserInfoUtil.getIUserAuth().removeUserAuth(UserInfoUtil.getClient(getRequest()));
			//登录成功后跳转后台界面
			view.setViewName("redirect:000000");
		}catch(Exception ex){
			if(ex instanceof BizException){
				if(null!=parseObject.getLoginUrl()){
					getRequest().setAttribute("backUrl",parseObject.getLoginUrl());	
				}
				getRequest().setAttribute("msg",((BizException)ex).getMsg());
				getRequest().setAttribute("errorCode",((BizException)ex).getCode());	
			}else{
				//异常性的登录
				getRequest().setAttribute("msg","登录失败，请重新登录再试");
			}
			//跳转到错误画面
			error500(view,getRequest());
		}
		return view;
	}
}
